/*
 * Created by Jaren at 2021/10/28 19:12
 */
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:get/get.dart';

class LoadingController extends GetxController {
    RxString msg = 'Loading...'.obs;

    Future<void> showLoading({autoDismiss = true, autoDismissDuration = 10}) async {
        var context = Get.overlayContext;
        if (context == null) return Future.error('Context is null!');
        Future f = showDialog(context: context, barrierDismissible: false, builder: (_) =>
            WillPopScope(
                onWillPop: () async => false,
                child: const Center(
                    child: SizedBox(
                        width: 60,
                        height: 60,
                        child: CircularProgressIndicator(
                            strokeWidth: 5,
                        ),
                    ),
                ),
            ),
        );
        if (autoDismiss) {
            await Future.delayed(Duration(seconds: autoDismissDuration));
            // Dismiss CircularProgressIndicator
            Navigator.of(context).pop();
        }
        return f;
    }

    dismissLoading() {
        var context = Get.overlayContext;
        if (context == null) return;
        Navigator.of(context).pop();
    }
}

class LoadingWidget extends StatelessWidget {
    @override
    Widget build(BuildContext context) {
        return GetBuilder<LoadingController>(
            init: LoadingController(),
            builder: (controller) =>
                AlertDialog(
                    content: Text(
                        controller.msg.value,
                        style: TextStyle(fontWeight: FontWeight.bold),
                    ),
                ),
        );
    }
}